<!DOCTYPE HTML>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8">
<head th:include="include :: header"></head>
<style type="text/css">
    .speed_box {
        width: 475px;
        height: 20px;
        display: none;
        border: 1px solid #0091f2;
        border-radius: 10px;
        overflow: hidden;
        margin-left: 200px;
        margin-top: 8px;
        margin-bottom: -5px;
    }

    #upload_speed {
        width: 0;
        height: 100%;
        background: #0091f2;
        color: white;
        text-align: center;
        line-height: 20px;
        font-size: 16px;
    }
</style>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-videoInfo-add">
        <div class="form-group">
            <label class="col-sm-3 control-label">上传视频：</label>
            <!--播放地址-->
            <input id="url" name="url" class="form-control" type="hidden">
            <div class="col-sm-4">
                <!--TODO 视频上传完成后截取一帧作为视频封面-->
                <!--<img src="/images/default-thumbnail.png" width="180" style="" id="imgpre">-->
                <input id="video" name="video" class="form-control" type="file"
                       onchange="uploadVideo(this);return false;">
            </div>
            <!--<a class="btn btn-success" onclick="$.operate.add()">-->
            <!--</a>-->
            <a class="btn btn-danger btn-del btn-del disabled" onclick="delete_video()">
                <i class="fa fa-remove"></i> 删除
            </a>
            <!--<a class="btn btn-danger btn-del btn-del disabled" onclick="open1('预览','',200, 100)">-->
            <a class="btn btn-danger btn-del btn-del disabled"
               onclick="preview_video('预览', $('#url').val(), 1000, 580);return false;">
                <!--<a class="btn btn-danger btn-del btn-del" onclick="$.modal.open_top('预览','',1000, 580)">-->
                <i class="fa fa-remove"></i> 预览
            </a>
            <div class="speed_box">
                <div id="upload_speed">0%</div>
            </div>
            <div id="video_preview"></div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">所属分类：</label>
            <div class="col-sm-8">
                <input id="videoTypeIds" name="videoTypeIds" type="hidden" >
                <select id="videoType1" class="form-control m-b" th:with="type=${@dict.getType('video_grade')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictCode}"></option>
                </select>
                <select id="videoType2" class="form-control m-b" th:with="type=${@dict.getType('video_subject')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictCode}"></option>
                </select>
                <select id="videoType3" class="form-control m-b" th:with="type=${@dict.getType('video_level')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictCode}"></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">讲师：</label>
            <div class="col-sm-8">
                <select id="teacherId" name="teacherId" class="form-control m-b">
                    <option th:each="teacherInfo : ${teacherInfos}" th:text="${teacherInfo.alias} + '(' + ${teacherInfo.name} + ')'" th:value="${teacherInfo.id}"></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">封面：</label>
            <div class="col-sm-8">
                <input id="facePicture" name="facePicture" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">标题：</label>
            <div class="col-sm-8">
                <input id="title" name="title" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">别名：</label>
            <div class="col-sm-8">
                <input id="alias" name="alias" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">简介：</label>
            <div class="col-sm-8">
                <input id="description" name="description" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">标签：</label>
            <div class="col-sm-8">
                <input id="tags" name="tags" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">视频格式, 如mp4, avi等：</label>
            <div class="col-sm-8">
                <input id="videoFormat" name="videoFormat" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">状态（0正常 1发布者可见 2管理员可见 3停用）：</label>
            <div class="col-sm-8">
                <input id="status" name="status" class="form-control" type="text">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">备注：</label>
            <div class="col-sm-8">
                <input id="remark" name="remark" class="form-control" type="text">
            </div>
        </div>
    </form>
</div>
<div th:include="include::footer"></div>
<link href="//vjs.zencdn.net/7.3.0/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/7.3.0/video.min.js"></script>
<script type="text/javascript">
    var videoType1_id = null;
    var videoType2_id = null;
    var videoType3_id = null;
    $(function () {
        videoType1_id = $("#videoType1").val()
        videoType2_id = $("#videoType2").val()
        videoType3_id = $("#videoType3").val()
    })

    $("#videoType1").on('change', function () {
        videoType1_id = $("#videoType1").val()
    });

    $("#videoType2").on('change', function () {
        videoType2_id = $("#videoType2").val()
    });

    $("#videoType3").on('change', function () {
        videoType3_id = $("#videoType3").val()
    });


    var prefix = ctx + "video/videoInfo"
    $("#form-videoInfo-add").validate({
        rules: {
            xxxx: {
                required: true,
            },
        }
    });

    function submitHandler() {
        if ($.validate.form()) {
            if (videoType1_id && videoType2_id && videoType3_id) {
                $("#videoTypeIds").val(videoType1_id + "," + videoType2_id + "," + videoType3_id);
            } else {
                parent.layer.alert('请选择正确的所属分类', {icon: 2, title: "系统提示"});
                return false;
            }
            $.operate.save(prefix + "/add", $('#form-videoInfo-add').serialize());
        }
    };

    function uploadVideo(fileDom) {
        //判断是否支持FileReader
        // debugger;
        var reader = null;
        if (window.FileReader) {
            reader = new FileReader();
        } else {
            parent.layer.alert('不支持FileReader API 请升级您的设备', {icon: 2, title: "系统提示"});
            return;
        }

        var video = fileDom.files[0];

        var videoType = /^video\//;
        //是否是视频
        if (!videoType.test(video.type)) {
            parent.layer.alert("文件格式错误，请上传视频类型,如：mp4,mkv,flv,avi等后缀的视频。", {icon: 2, title: "系统提示"});
            return;
        }

        //显示上传进度条
        $('.speed_box').show();

        //读取完成
        // reader.readAsDataURL(video); 只能用于读取图片
        reader.readAsBinaryString(video);

        reader.onload = function (e) {
            var formData = new FormData();
            formData.append('video', video);

            $.ajax({
                url: ctx + 'video/video/add',
                type: 'POST',
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                // xhrFields : {
                //     withCredentials : true
                // },
                // crossDomain : true,
                async: true,
                dataType: 'json',
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $('#url').attr('value', result.msg);
                        //上传视频成功后，置为disabled，则整个表单提交时，不会再把视频提交一次
                        $('#video').attr('disabled', 'true');
                        //上传视频成功后，可删除、预览
                        $('#video').parent().nextAll('.disabled').removeClass('disabled');
                        $.modal.msgSuccess('上传视频成功');
                    } else {
                        $.modal.alertError('上传视频失败');
                    }
                    //隐藏进度条
                    $('.speed_box').hide()
                    // $.modal.closeLoading();
                },
                xhr: function () { //获取ajaxSettings中的xhr对象，为它的upload属性绑定progress事件的处理函数
                    var xhr = $.ajaxSettings.xhr();
                    if (onprogress && xhr.upload) { //检查upload属性是否存在
                        //绑定progress事件的回调函数
                        xhr.upload.addEventListener('progress', onprogress, false);
                        return xhr;
                    }
                }
            })
        };
    };

    //侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次
    function onprogress(event) {
        var event = event || window.event;
        //console.log(event);  //事件对象
        // console.log("已经上传：" + event.loaded); //已经上传大小情况(已上传大小，上传完毕后就 等于 附件总大小)
        //console.log(event.total);  //附件总大小(固定不变)
        var loaded = Math.floor(100 * (event.loaded / event.total)); //已经上传的百分比
        $("#upload_speed").html(loaded + "%").css("width", loaded + "%");
    };

    //删除视频
    function delete_video() {
        $.modal.confirm("确认要删除该视频吗?", function () {
            var url = ctx + 'video/video/remove';
            var value = $('#url').attr('value');
            var data = {"url": value};
            $.modal.loading("正在处理中，请稍后...");
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                data: data,
                success: function (result) {
                    $.modal.closeLoading();
                    if (result.code == web_status.SUCCESS) {
                        $('#url').attr('value', '');
                        $('#video').removeAttr('disabled').val('');
                        // $('#video').attr('disabled', 'false').removeClass('disabled');
                        $('#video').outerHTML = $('#video').outerHTML;
                        $('#video').parent().nextAll('a.btn').addClass('disabled');
                        $.modal.msgSuccess('删除视频成功');
                    } else {
                        $.modal.alertError('删除视频失败');
                    }
                }
            })
        });
    };

    //预览视频
    function preview_video() {
        var video_dom = '<video id="video_dom" width="100%" height="100%" controls="controls"  src=' + video_url + '></video>';
        $('#video_preview').html(video_dom);
    };

    function preview_video(title, url, width, height) {
        //将文件路径进行转义
        url = url.replace(new RegExp(":", "gm"), "@")
        url = url.replace(new RegExp("/", "gm"), "-")
        url = url.replace(/\\/g, "-")
        alert(url);
        var video_url = ctx + 'video/video/preview/?videoUrl=' + url + '';
        // var video_html = "<div id=\"pre_view_div\">" +
        //                  "    <video width=\"320\" height=\"240\" controls preload=\"auto\">\n" +
        //                  // "        <source src=\"" + encodeURIComponent(video_url) + "\" type=\"video/mp4\">\n" +
        //                  "        <source src=\"" + video_url + "\">\n" +
        //                  "        您的浏览器不支持 video 标签。\n" +
        //                  "    </video>\n" +
        //                  "</div>"
        var video_html = "   <video\n" +
            "            id=\"my-player\"\n" +
            "            class=\"video-js\"\n" +
            "            controls\n" +
            "            preload=\"auto\"\n" +
            "            poster=\"//vjs.zencdn.net/v/oceans.png\"\n" +
            "            data-setup='{}'>\n" +
            "        <source src=\"" + video_url + "\" type=\"video/mp4\"></source>\n" +
            "        <p class=\"vjs-no-js\">\n" +
            "            To view this video please enable JavaScript, and consider upgrading to a\n" +
            "            web browser that\n" +
            "            <a href=\"http://videojs.com/html5-video-support/\" target=\"_blank\">\n" +
            "                supports HTML5 video\n" +
            "            </a>\n" +
            "        </p>\n" +
            "    </video>"
        //如果是移动端，就使用自适应大小弹窗
        if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
            width = 'auto';
            height = 'auto';
        }

        window.parent.top.layer.open({
            type: 1,
            area: [width + 'px', height + 'px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: title,
            content: video_html,
            btn: ['确定', '关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            yes: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler();
            },
            cancel: function (index) {
                return true;
            },
        });
    };

    function replaceAll(str, oldWord, newWord) {
        if (str != null)
            str = str.replace(/oldWord/g, newWord)
        return str;
    };
</script>
</body>
</html>
